//
//  Array+Extensions.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/17.
//

import UIKit

extension Array {
    func toJsonstring() -> String {
        if (!JSONSerialization.isValidJSONObject(self)) {
            print("无法解析出JSONString")
            return " "
        }
        if let data = try? JSONSerialization.data(withJSONObject: self, options: [.fragmentsAllowed,.prettyPrinted]),
           let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) as String? {
            let result2 = JSONString.replacingOccurrences(of: "\n", with: "")
            let result3 = result2.replacingOccurrences(of: " ", with: "")
            return result3
        }
        return " "
    }
    
    func uniqued<H: Hashable>(_ filter: (Element) -> H) -> [Element] {
        var result = [Element]()
        var map = [H: Element]()
        for ele in self {
            let key = filter(ele)
            if map[key] == nil {
                map[key] = ele
                result.append(ele)
            }
        }
        return result
    }
   
    subscript (safe index: Index) -> Iterator.Element? {
          return indices.contains(index) ? self[index] : nil
    }
}
